// pages/house/RentalHouseDetail/newHouseShare/newHouseShare

import api from "../../../../common/api";
import util from "../../../../utils/util";

const app = getApp()

// 相对单位
let rpx = 1;
// 图片保存到本地的路径
let saveImgPromise = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    canvasHidden: false,
    content: {},
    QrCode: "",
    jingjiId: {},
    hasAgree: false,
    max: "",
    copyShowDialog: false,
    canvasWidth: 0,
    canvasHeight: 500,
    avatar: "",
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("进入分享房源", options);
    app.globalData.loginPromise
      .then(() => {
        wx.showShareMenu({ withShareTicket: true })
        var that = this;

        var content = app.globalData.houseShareBannerInfo.roomDetail || {
          "eletricity_type": "暂无信息",
          "water_type": "暂无信息",
          "heating_type": "暂无信息",
          "id": "48328f49e61344a08768e13b3a28d4d4",
          "resblock_name": "奉贤宝龙城市广场",
          "title": "奉贤宝龙城市广场",
          "turn_in_time": "",
          "resblock_type": "onSale",
          // "first_picture_url": "https://api.shulanfd.com/aist-filesvr-web/api/files/7d712aa364ef492a94a07350d45ee428",
          "first_picture_url": "https://image1.ljcdn.com/newhcms/phpH3IcTt1470197977.png.592x432.jpg",
          "picture_num": 100,
          "house_type": "商业",
          "area": "奉贤",
          "street": "南桥",
          "average_price": 23000,
          "developer": "上海贤通置业有限公司",
          "opentime": "2014-06-30 00:00:00",
          "address": "环城东路732弄",
          "build_type": "未知",
          "certificate": "40",
          "volume_rate": "2.83",
          "greening_rate": "20%",
          "park_num": 1166,
          "park_rate": "1:3",
          "build_size": 182546,
          "total_size": 40687,
          "property_company": "泰安宝龙商业物业管理有限公司",
          "hd_new_house_resblock_id": "7b3c860873fe4958b242d81e831bb2fb",
          "house_status": "AVAILABLE",
          "isNewHouse": true
        }

        var jingjiId = app.globalData.houseShareBannerInfo.allId || {
          "agentId": "eeffd30ae7a94971a697b4fd4bae5701",
          "storeId": "5b4a6ab5b6134baabe5638f9e05b7650",
          "mkId": "EMP",
          "houDelId": "48328f49e61344a08768e13b3a28d4d4",
          "newHouse": "new",
          "realName": "用户13665205105",
          "mobile": "13665205105",
          "wxHeadImg": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLibWZaJnsQQpBNTmbrWEtNmA81pRvzTHjolyT5avbMclcAXuxhR3gfNkJzUpHR8c6u7GEETb2tWicw/132"
        }

        console.log("【content】", content);
        console.log("【jingjiId】", jingjiId);

        this.setData({
          content: content,
          jingjiId: jingjiId,
          avatar: jingjiId.wxHeadImg
        })

        // 删除太长的头像
        delete jingjiId.wxHeadImg

        var QrCode;
        //长链接--短
        api.qrcodeLongToShort(JSON.stringify(jingjiId), {}, res => {
          console.log(res)
          let smallCode = res.data.content;
          QrCode = util.domain + "miniCode/getWXACodeUnlimit?page=" + encodeURI("pages/houseShare/newRentalHouseDetail/newRentalHouseDetail") + "&scene=" + smallCode + "&miniName=zhaofangjs"
          console.log('生成二维码==', QrCode);
          that.setData({
            QrCode: QrCode
          })

          saveImgPromise = Promise.all([
            this.data.content.first_picture_url,
            this.data.QrCode,
            this.data.avatar
          ].map((url) => {
            return this.saveImgToPhotosAlbumTap(url)
          }))
        })
      })
  },

  saveImgToPhotosAlbumTap(value) {
    console.log("源图片地址==", value);

    return new Promise((resolve, reject) => {
      if (!value) return resolve("")
      wx.getImageInfo({
        src: value,
        success: function(res) {
          console.log("promise===", value, res.path);

          resolve(res.path)
        },
        fail: () => {
          this.saveImgToPhotosAlbumTap(app.globalData.defaultHouseUrl)
            .then(resolve)
        }
      })
    })
  },

  drawCanvas() {
    const content = this.data.content
    const jingjiId = this.data.jingjiId

    wx.showLoading({
      title: '加载中',
    })

    return new Promise((resolve, reject) => {
      saveImgPromise.then((result) => {
        // console.log("开始画图", (new Date()).getSeconds());

        let context = wx.createCanvasContext('share') //这里的“share”是“canvas-id”
        context.clearRect(0, 0, 375 * rpx, this.data.canvasHeight)

        context.setFillStyle('#eee')
        context.fillRect(0, 0, 375 * rpx, this.data.canvasHeight)

        context.drawImage(result[0] || "/images/detail_banner.jpg", 0, 0, 375 * rpx, 260) //绘制房源图

        context.setFillStyle('#fff') //绘制白色
        context.fillRect(20, 280, 375 * rpx - 20 * 2, this.data.canvasHeight - 260 - 20 * 2)

        context.drawImage("/images/haofangzi.png", 20, 290, 225 / 2, 73 / 2) //icon
        context.drawImage("/images/hot.png", 375 * rpx - 50 - 30, 300, 50 / 2, 87 / 2) //hot

        context.setFontSize(20 * rpx)
        context.setFillStyle("#333")
        context.fillText(`单价：${content.average_price||""}元`, 30, 350)
        context.fillText(`小区：${content.resblock_name||""}`, 30, 380)

        this.drawCirImage(context, 50, 50, 30, 400, result[2] || "/images/default_head.png")

        context.setFontSize(20 * rpx)
        context.fillText(jingjiId.realName || "", 90, 420)
        context.setFontSize(16 * rpx)
        context.fillText(jingjiId.mobile || "", 90, 444)

        context.drawImage(result[1] || "", 375 * rpx - 60 - 20 - 10, 393, 60, 60) //二维码

        context.draw(true, () => {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 375 * rpx,
            height: this.data.canvasHeight,
            destWidth: 375 * rpx * 4,
            destHeight: this.data.canvasHeight * 4,
            canvasId: 'share',
            success: a => {
              wx.hideLoading()

              resolve(a.tempFilePath)
            },
            fail: (err) => {
              console.log("绘制error", err);
            }
          })
        })
      })
    })
  },

  hanldeSaveImage() {
    this.drawCanvas()
      .then((tempFilePath) => {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success: () => {
            // console.log("保存海报成功", (new Date()).getSeconds());
          },
          fail: () => {
            wx.getSetting({
              success: (res) => {
                if (!res.authSetting['scope.writePhotosAlbum']) {
                  wx.showModal({
                    title:'提示',
                    content:'需要获取图片权限哦',
                    success: (res) => {
                      if (res.confirm) {
                        wx.openSetting()
                      }
                    }
                  })
                }
              }
            })
          }
        })
      })
  },

  hanldePreviewImage() {
    this.drawCanvas()
      .then((tempFilePath) => {
        wx.previewImage({
          urls: [tempFilePath]
        })
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.getSystemInfo({
      success: (res) => {
        rpx = res.windowWidth / 375

        this.setData({
          canvasWidth: 375 * rpx,
          canvasHeight: 500 || res.windowHeight, //暂时固定高度
        })
      }
    })
  },

  //绘制圆形图片
  drawCirImage(contex, width, heigth, x, y, img) {
    var contex = contex
    var avatarurl_width = width; //绘制的头像宽度
    var avatarurl_heigth = heigth; //绘制的头像高度
    var avatarurl_x = x; //绘制的头像在画布上的位置
    var avatarurl_y = y; //绘制的头像在画布上的位置
    contex.save();
    contex.beginPath(); //开始绘制
    //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
    contex.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);

    contex.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因

    contex.drawImage(img, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片，必须是https图片

    contex.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制

    contex.draw(); //可将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
})